from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django import http
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect

# Create your views here.
from django.views import View

from carts.utils import merge_cookie_redis_cart
from meiduo_mall.libs import sinaweibopy3
from meiduo_mall.utlis.response_code import RET
from .models import OAuthQQUser, OAuthSinaUser
from .utils import decode_openid,encode_openid
from users.models import User

#获取QQ登陆解码
class QQLoginView(View):
    def get(self,request):
        # 1,获取参数
        state=request.GET.get('next','/')
        # 2,创建OAuthQQ对象,从dev配置的qq参数取值
        oauth_qq=OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                         client_secret=settings.QQ_CLIENT_SECRET,
                         redirect_uri=settings.QQ_REDIRECT_URI,
                         )
        #3.获取qq登陆页面
        login_url=oauth_qq.get_qq_url()
        #4.返回响应,请求的是ajax,所以返回的是json格式
        return http.JsonResponse({"login_url":login_url})

        pass

#2.绑定qq用户和美多用户
class QQAuthUserView(View):
    def get(self,request):
        #1,获取参数(code,state)
        code = request.GET.get("code")
        state = request.GET.get("state","/")

        #2,校验code是否为空
        if not code:
            return http.HttpResponseForbidden("code丢失")

        #3,获取access_token
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                client_secret=settings.QQ_CLIENT_SECRET,
                redirect_uri=settings.QQ_REDIRECT_URI,
                state=state
                )

        access_token = oauth_qq.get_access_token(code)

        #4,获取openid
        openid = oauth_qq.get_open_id(access_token)

        #5.通过openid,查询qq授权用户,即我获取到了openid美多表里是否存在
        try:
            oauth_qq_user=OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            #5.1 初次授权,加密openid,返回授权页面
            encrypt_openid=encode_openid(openid)

            #注意这里的token要与前端保持 一致,不能随便写
            context={'token':encrypt_openid}

            #5.2返回授权页面,并携带加密了的openid
            return render(request,'oauth_callback.html',context=context)
            pass

        else:
            #6.1 非初次授权,获取美多用户
            user=oauth_qq_user.user

            #6.2状态保持,login是系统自带的状态保持函数,传入user即可
            login(request,user)

            #6.3返回响应
            response=redirect('/')
            response.set_cookie('username',user.username)
            response = merge_cookie_redis_cart(request,response, user)
            return response

    def post(self,request):

        # 1,获取参数
        openid=request.POST.get("access_token")
        mobile = request.POST.get("mobile")
        password = request.POST.get("pwd")
        sms_code = request.POST.get("sms_code")

        # 2,校验参数
        # 2,1 为空校验
        if not all([openid,mobile,password,sms_code]):
            return http.HttpResponseForbidden('参数不全')

        #2.2校验openid
        openid=decode_openid(openid)

        if not openid:
            return http.HttpResponseForbidden('openid已过期')

        # 2.3 验证账号密码 authenticate系统提供的方法
        user=authenticate(request,username=mobile,password=password)

        # 3.数据入库,判断用户对象
        if user:
            #3,1 创建qq授权对象
            oauth_qq_user = OAuthQQUser()

            ##3,2 关联美多用户和 openid
            oauth_qq_user.user=user
            oauth_qq_user.openid=openid
            #3.3.数据入库
            oauth_qq_user.save()

            ##3,4 状态保持,返回响应,login是我们定义保持状态的函数,传参就行
            login(request,user)
            response=redirect('/')
            #返回主页的时候顺带用户cookie便于知道谁登陆了
            response.set_cookie('username',user.username)
            response = merge_cookie_redis_cart(request, response, user)
            return response
        else:

           #4.1创建美多用户
            user=User.objects.create_user(username=mobile,password=password)

           #4.2创建qq授权对象
            oauth_qq_user=OAuthQQUser()
            # 4,3 关联美多用户和openid,入库
            oauth_qq_user.user=user
            oauth_qq_user.openid=openid
            oauth_qq_user.save()


            #4.状态保持,返回响应
            login(request,user)
            response = redirect('/')
            response.set_cookie("username", user.username)
            response = merge_cookie_redis_cart(request, response, user)
            return response



#获取微博登陆解码
class OAuthSinaURLView(View):
    def get(self,request):
        #获取参数
        next = request.GET.get('next', '/')
        # 创建授权对象

        oauth_sina = sinaweibopy3.APIClient(app_key=settings.APP_KEY,
                                        app_secret=settings.APP_SECRET,
                                        redirect_uri=settings.REDIRECT_URL)
        # 生成微博授权地址

        login_url = oauth_sina.get_authorize_url()


        return http.JsonResponse({"login_url":login_url})

class SinaAuthUserView(View):
    def get(self,request):
        #1.获取code
        code=request.GET.get("code")

        #2.判空
        if not code:
            return http.JsonResponse("code丢失")
        #3创建对象
        oauth_sina = sinaweibopy3.APIClient(app_key=settings.APP_KEY,
                                            app_secret=settings.APP_SECRET,
                                            redirect_uri=settings.REDIRECT_URL)
        # 3,1获取access_token
        result=oauth_sina.request_access_token(code)
        oauth_sina.set_access_token(result.access_token,result.expires_in)
        openid=result.uid

        #判断是否初次授权
        try:
            sinauser=OAuthSinaUser.objects.get(uid=openid)
        except Exception:
            #初次授权则加密openid，并返回授权页面
            encrypt_openid=encode_openid(openid)

            #返回数据
            context={'token':encrypt_openid}
            return render(request,'oauth_callback.html',context)
        else:
            #非初次授权，则保持状态，转到主页
            user=sinauser.user

            # 状态保持,login是系统自带的状态保持函数,传入user即可
            login(request, user)

            #重定向到主页
            response=redirect('/')
            #cookie设置
            response.set_cookie()
            return response
    #绑定美多用户与微博用户
    def post(self,request):

        # 1,获取参数
        openid=request.POST.get("access_token")
        mobile = request.POST.get("mobile")
        password = request.POST.get("pwd")
        sms_code = request.POST.get("sms_code")

        # 2,校验参数
        # 2,1 为空校验
        if not all([openid,mobile,password,sms_code]):
            return http.HttpResponseForbidden('参数不全')

        #2.2校验openid
        openid=decode_openid(openid)

        if not openid:
            return http.HttpResponseForbidden('openid已过期')

        # 2.3 验证账号密码 authenticate系统提供的方法
        user=authenticate(request,username=mobile,password=password)

        # 3.数据入库,判断用户对象
        if user:
            #3,1 创建qq授权对象
            oauth_sina_user = OAuthSinaUser()

            ##3,2 关联美多用户和 openid
            oauth_sina_user.user=user
            oauth_sina_user.uid=openid
            #3.3.数据入库
            oauth_sina_user.save()

            ##3,4 状态保持,返回响应,login是我们定义保持状态的函数,传参就行
            login(request,user)
            response=redirect('/')
            #返回主页的时候顺带用户cookie便于知道谁登陆了
            response.set_cookie('username',user.username)
            response = merge_cookie_redis_cart(request, response, user)
            return response
        else:

           #4.1创建美多用户
            user=User.objects.create_user(username=mobile,password=password)

           #4.2创建新浪授权对象
            oauth_sina_user=OAuthSinaUser()
            # 4,3 关联美多用户和openid,入库
            oauth_sina_user.user=user
            oauth_sina_user.uid=openid
            oauth_sina_user.save()


            #4.状态保持,返回响应
            login(request,user)
            response = redirect('/')
            response.set_cookie("username", user.username)
            response = merge_cookie_redis_cart(request, response, user)
            return response
